package com.example.demo.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.demo.dao.UserMapper;
import com.example.demo.dao.model.Users;
import com.example.demo.util.ToolUtil;
import com.example.demo.validation.UserParams;

@Service
@Transactional
public class UserService {

	@Autowired
	private UserMapper userMapper;
	
	public Integer getCount() {
		return userMapper.getCount(); 
	}
	
	public List<Users> getUserListByCondition(String cond) {
		return userMapper.getUserListByCondition(cond);
	}
	
	public Map<String, Object> getProfileByUserCode(String userCode) {
		return userMapper.getProfileByUserCode(userCode);
	}
	
	@Transactional
	@SuppressWarnings("unchecked")
	public Integer addUser(Map<String, Object> params, String ip) {
		String addType = (String)params.get("addType");
		Object data = params.get("data");
		List<HashMap<String, Object>> batchData = new ArrayList<HashMap<String, Object>>();
		if(addType.equals("one")) {
			HashMap<String, Object> model = (HashMap<String, Object>) data;
			model.put("user_code", ToolUtil.getUUID());
			model.put("create_user", "system");
			model.put("ip", ip);
			batchData.add(model);
		} else if (addType.equals("batch")) {
			batchData = (List<HashMap<String, Object>>) data;
			for(HashMap<String, Object> model : batchData) {
				model.put("user_code", ToolUtil.getUUID());
				model.put("create_user", "system");
				model.put("ip", ip);
			}
		}
		if(batchData.size() == 0) {
			return 0;
		}
		return userMapper.addUserBatch(batchData);
	}
	
	@Transactional
	public Integer deleteByUserCode(String userCode) {
		return userMapper.deleteByUserCode(userCode); 
	}
	
	@Transactional
	public void autoAdd(Integer size, String ip) {
		
		List<HashMap<String, Object>> batchData = new ArrayList<HashMap<String, Object>>();
		for(int i = 0; i < size; i++) {
			String uuid = ToolUtil.getUUID();
			@SuppressWarnings("serial")
			HashMap<String, Object> data = new HashMap<String, Object>(){
				{
					put("user_code", uuid);
					put("name", uuid);
					put("age", 24);
					put("amount", 0);
					put("is_vip", false);
					put("create_user", "system");
					put("ip", ip);
					put("nickname", "nickname-"+uuid);
				}
			};
			batchData.add(data);
		}
		userMapper.addUserBatch(batchData);
	}
	
	@Transactional
	public Integer update(UserParams params) {
		System.out.println(params);
		Integer ret = userMapper.updateUser(params);
		if(ret == 0) {
			return 0;
		}
		ret += userMapper.updateProfile(params);
		return ret;
	}
	
}
